/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData } from '@amcax/base';
import { previewer } from '@app-cad/module';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { wsApi } from '@app-cad/server';
import { FeatureBaseCommand, FeaturedCmdDialogParams } from '@app-cad/types';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';
import { isEmpty } from 'lodash';

enum ThicknessMode {
  BLIND = 'Blind',
  MIDPLANE = 'Midplane',
}

type FormData = {
  mode: ThicknessMode;
  base: pickedFaceData[];
  offset: number;
  reverse1: boolean;
  useDir2: boolean;
  offset2: number;
  reverse2: boolean;
};

type Params = {
  mode: ThicknessMode;
  base: string[];
  isCutter: boolean;
  offset: number;
  reverse1: boolean;
  useDir2: boolean;
  offset2: number;
  reverse2: boolean;
};

function CommandThickness({ title, onClose, props }: FeaturedCmdDialogParams) {
  const initData = {
    mode: ThicknessMode.BLIND,
    base: [],
    offset: 10,
    reverse1: false,
    useDir2: false,
    offset2: 20,
    reverse2: false,
  };
  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useEffect(() => {
    previewAction();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { mode, base, offset, reverse1, useDir2, offset2, reverse2 } = params;

    await initEditDependency(base);

    setFormData({
      mode: mode,
      base: base.map(
        (item) => picker.generatePickObjByPickID(item) as pickedFaceData,
      ),
      offset: offset,
      reverse1: reverse1,
      useDir2: useDir2,
      offset2: offset2,
      reverse2: reverse2,
    });
  }, [props?.shape]);

  const isFormDataValid = () => {
    const { mode, base, offset, useDir2, offset2 } = formData;
    if (
      (mode === ThicknessMode.BLIND && !useDir2) ||
      mode === ThicknessMode.MIDPLANE
    ) {
      return !isEmpty(base) && offset != null && offset != 0;
    } else if (mode === ThicknessMode.BLIND && useDir2) {
      return (
        !isEmpty(base) &&
        offset != null &&
        offset != 0 &&
        offset2 != null &&
        offset2 != 0
      );
    } else {
      return false;
    }
  };
  const finishValid = useMemo(isFormDataValid, [formData]);
  const checkAndFinish = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, previewInCommand } = useCommand('cmd-thickness', {
    onClose,
    finishDraw: checkAndFinish,
  });

  const execute = async (preview: boolean = false) => {
    const { mode, base, offset, reverse1, useDir2, offset2, reverse2 } =
      formData;
    const baseID = base.map((item) => getIdOfPickedObj(item));
    const params: Params = {
      mode: mode,
      base: baseID,
      isCutter: false,
      offset: offset,
      reverse1: reverse1,
      useDir2: useDir2,
      offset2: offset2,
      reverse2: reverse2,
    };
    const res =
      props == null
        ? await wsApi.createThickness(params, preview)
        : await wsApi.setParams((props as any).shape, params, preview);

    if (preview) {
      await previewInCommand(res);
    }

    return res;
  };

  const schema = useMemo(() => {
    const modeSchema = {
      type: 'string',
      title: '模式',
      default: ThicknessMode.BLIND,
      oneOf: [
        {
          type: 'string',
          title: '给定厚度',
          const: ThicknessMode.BLIND,
        },
        {
          type: 'string',
          title: '中间平面',
          const: ThicknessMode.MIDPLANE,
        },
      ],
    };

    // 中间平面
    if (formData.mode === ThicknessMode.MIDPLANE) {
      return {
        properties: {
          mode: modeSchema,
          base: {
            type: 'array',
            title: '目标曲面',
            items: {
              type: 'string',
              enum: [],
            },
            uniqueItems: true,
            format: PickInputRJSFFormat.MultiPickFace,
          },
          offset: {
            type: 'number',
            title: '厚度',
            default: 10,
            format: NumberInputFormat.Length,
          },
        },
      };
    }

    // 给定厚度
    if (formData.mode === ThicknessMode.BLIND) {
      return {
        properties: {
          mode: modeSchema,
          base: {
            type: 'array',
            title: '目标曲面',
            items: {
              type: 'string',
              enum: [],
            },
            uniqueItems: true,
            format: PickInputRJSFFormat.MultiPickFace,
          },
          offset: {
            type: 'number',
            title: '厚度1',
            default: 10,
            format: NumberInputFormat.Length,
          },
          reverse1: {
            type: 'boolean',
            title: '反转方向',
            default: false,
          },

          offset2: formData.useDir2
            ? {
                type: 'number',
                title: '厚度2',
                default: 20,
                format: NumberInputFormat.Length,
              }
            : {},
          reverse2: formData.useDir2
            ? {
                type: 'boolean',
                title: '反转方向',
                default: false,
              }
            : {},
          useDir2: {
            type: 'boolean',
            title: '双侧',
            default: false,
          },
        },
      };
    }

    return schema;
  }, [formData.mode, formData.useDir2]);

  const previewAction = async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }
    await execute(true);
  };
  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={false}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        v.useDir2
          ? setFormData({
              ...v,
              reverse2:
                formData.reverse1 !== v.reverse1 ? !v.reverse2 : v.reverse2,
            })
          : setFormData(v);
      }}
      extraUiSchema={{
        base: {
          'ui:placeholder': '请输入曲面',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinish}
      noValidate
    />
  );
}

export const cmdThickness: FeatureBaseCommand = {
  id: 'CmdThickness',
  label: 'command.thickness',
  icon: 'commands/feature/thickeness',
  create: (label, onClose, props) => (
    <CommandThickness
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
